﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Koolwired.Imap;
using anmar.SharpMimeTools;
using System.IO;

namespace Mailer.Utilities.MailParser
{
	public class Parser
	{
		public static ResultInfo Parse(string rawmailbody)
		{
			rawmailbody = rawmailbody.Trim();

			ResultInfo ret = new ResultInfo();
			ret.Status = ResultStatus.Unknown;

			Logger.Debug(typeof(Parser), "parsing: " + rawmailbody.Length + " characters");


			byte[] rawbytes = Encoding.ASCII.GetBytes(rawmailbody);

			MemoryStream ms = new MemoryStream(rawbytes);

			SharpMimeMessage sm2 = new SharpMimeMessage(ms);
			walk(sm2);
			/*
			Logger.Debug(typeof(Parser), "subject: " + sm2.Header.Subject);

			foreach (object h in sm2.Header)
			{
				Logger.Debug(typeof(Parser), "header: " + h + " = " + sm2.Header[h]);

			}
			*/

			Logger.Debug(typeof(Parser), "");

			return ret;
		}

		static void walk(SharpMimeMessage m)
		{
			Logger.Debug(typeof(Parser), "message: " + m.Header.ContentType);
			Logger.Debug(typeof(Parser), "subject: " + m.Header.Subject);
			Logger.Debug(typeof(Parser), "multipart: " + m.IsMultipart);

			foreach (object h in m.Header)
			{
				Logger.Debug(typeof(Parser), "header: " + h + " = " + m.Header[h]);
			}

			Logger.Debug(typeof(Parser), "raw headers: " + m.Header.RawHeaders);
			
			if (m.IsMultipart)
			{
				for (int j = 0; j < m.PartsCount; j++)
				{
					SharpMimeMessage m2 = m.GetPart(j);
					walk(m2);
				}
			}

		}
	}
}
